import React from 'react'
import { Form, Input, Button, Message ,Icon,Row,Col} from 'antd';
import api from '../../../api/binding';
const urlTools = require('url');
const FormItem = Form.Item;


import PanelBox from '../../../components/PanelBox';

import './index.less'

class ManageForm extends React.Component {
  state = {
    loading: false,
    sendcode: '发送验证码',
  };
  submit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({
          loading: true
        });
        api.put('/bindingEmail', 
        { 
          ...values ,
          bindtoken:this.state.bindtoken
        }).then((res) => {
          const result = res.data;
          if (result.code == 0) {
            Message.success('绑定成功！');
            this.props.form.resetFields();
          } else {
            Message.error(result.message);
            if (result.messages) {
              result.messages.forEach(item => {
                var obj = {};
                obj[item.field] = {
                  value: values[item.field],
                  errors: [new Error(item.error)]
                }
                this.props.form.setFields(obj);
              });
            }
          }
          this.setState({
            loading: false
          });
        }).catch(e=>{
          Message.error("绑定失败");
          this.setState({
            loading: false
          });
        });
      }
    });
  }


 clear = () => {
    this.props.form.resetFields();
  }


 Binding = (params = {}) => {
  const email =  this.props.form;
//  this.checkBinding;
  const formData = this.props.form.getFieldsValue();
  if (email.getFieldValue('email')==null) {
    Message.warning("请输入您的邮箱");
    return ;
    }
  api.put('/binding',formData).then((data) => {
    if (data.data.code == 0) {
      this.setState({
        bindtoken:data.data.data,
      });
      let i = 60;
      let timer = setInterval(() => {
        this.setState({
          sendcode: i--+"秒后可从新发送"
        });
        if (i == 0) {
          clearInterval(timer);
          this.setState({
            sendcode: '发送验证码',
            disabledMailSend: false
          });
        }
      }, 1000);
      Message.success("验证码已发送");
    } else {
      Message.error(data.data.message);
      if (data.data.messages) {
        data.data.messages.forEach(item => {
          var obj = {};
          obj[item.field] = {
            value: formData[item.field],
            errors: [new Error(item.error)]
          }
          this.props.form.setFields(obj);
        });
      }
      //Message.error("验证码发送失败");
    }
  });
} 
  

checkBinding = (rule, value, callback) => {
  const form = this.props.form;
  if (value && value !== form.getFieldValue('email')) {
    callback('请输入您的邮箱!');
  } else {
    callback();
  }
}
  /* checkConfirm = (rule, value, callback) => {
    const form = this.props.form;
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    callback();
  } */

  handleConfirmBlur = (e) => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  }

  changeUrl = (url) => {
    let obj = urlTools.parse(url, true);
    let urlPrefix = url.substring(0, url.indexOf("?"));
    return urlPrefix + "?bindToken=" + obj.query.bindToken + "&random=" + Math.ceil(Math.random() * 9000 + 1000);
  }

  changeImage = (event) => {
    this.setState({
      captcha: this.changeUrl(this.state.captcha)
    })
  }

  config = (params = {}) => {
    clearForm: () => {
      this.props.form.resetFields();
    },
      api.get("/getCaptchabind").then((res) => {
        let data = res.data;
        if (data.code == 0) {
          this.setState({
            captcha: data.data.imageCaptchaUrl + "&random=" + Math.ceil(Math.random() * 9000 + 1000)
          });
          this.props.form.setFieldsValue({
            imageCaptchaToken: data.data.imageCaptchaToken
          })
        }
      }).catch((e) => {
        Message.error("载入失败,请稍后在试");
      });
  }

email= () =>{
  const formData = this.props.form.getFieldsValue();
  api.put('/binding',formData).then((data) => {
    if (data.data.code == 0) {
    } else {
     // Message.error(data.data.message);
      if (data.data.messages) {
        data.data.messages.forEach(item => {
          var obj = {};
          obj[item.field] = {
            value: formData[item.field],
            errors: [new Error(item.error)]
          }
          this.props.form.setFields(obj);
        });
      }
      //Message.error("验证码发送失败");
    }
  });
}


  componentDidMount = () => {
    this.config();
    this.email();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 9 },
      wrapperCol: { span: 7 },
    };

    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 15,
          offset: 9,
        },
        sm: {
          span: 15,
          offset: 9,
        },
      },
    };
    const bindingformItemLayout = {
      wrapperCol: {
         xs: {
           span: 1,
           offset: 18,
         },
         sm: {
           span: 1,
           offset: 11,
         },
       },
     };
   
    return (
      <Form onSubmit={this.submit}>
       {getFieldDecorator('imageCaptchaToken', {
            })(
              <Input type="hidden" />
              )}
       <Row>
       <Row>
       <Col span="16" offset="2">
        <FormItem
            {...formItemLayout}
                label="邮箱"
                hasFeedback
          >
           {getFieldDecorator('email', {
                 rules: [{
                           type: 'email', message: '输入邮箱的类型错误'
                 }, {
                           required: true, message: '请输入您的邮箱'
                 },
                {
                  validator: this.checkBinding
                }]
                 })(
                  <Input   type="email" className="content_style" addonBefore={<Icon type="mail" />} />
              )}
          </FormItem>
          </Col>
          </Row>
          <Row>
          <Col span="4" offset="8">
            <FormItem
            >
              {getFieldDecorator('imageCode', {
                rules: [{ required: true, message: '图片验证码不能为空!' },
                { min: 4, message: '图片验证码为4个字符' },
                { max: 4, message: '图片验证码为4个字符' }],
              })(
                <Input prefix={<Icon type="code-o" style={{ fontSize: 13 }} />} placeholder='请输入4位验证码,点击图片切换' style={{with:'100px'}}/>
                )}
            </FormItem>
          </Col>
          <Col span="4"  offset="1">
          <img className="image-code" src={this.state.captcha} onClick={this.changeImage.bind(this)} />
          </Col>
          </Row>
          <Row>
          <Col span="16" offset="2">
          <FormItem
            {...formItemLayout}
            label="验证码"
            hasFeedback
            >
            {getFieldDecorator('verificationcode', {
              rules: [{ required: true, message: '验证码不能为空!' },
              { min: 4, message: '请输入4个字符的验证码' },
              {
                validator: this.checkConfirm,
              }],
              initialValue: ''
            })(
              <Input  prefix={<Icon type="code-o" style={{ fontSize: 13 }} />} placeholder='请输入4位邮箱验证码' />
              )}
          </FormItem>
          </Col>
          <Col>
          <Button type="primary" onClick={this.Binding} style={{marginLeft:'-220px',marginTop:'2px'}} >{this.state.sendcode}</Button>
          </Col>
          </Row>
        <FormItem {...tailFormItemLayout}>
          <Button loading={this.state.loading} type="primary" htmlType="submit" size="large" style={{ marginRight: '10px' }}>绑定</Button>
          <Button onClick={this.clear} disabled={this.state.loading}>清空</Button>
        </FormItem>
        </Row>
      </Form>
    );
  }
}

const BindingForm = Form.create()(ManageForm);

export default class Binding extends React.Component {
  render() {
    return (
      <PanelBox>
        <div className="password-content">
          <BindingForm/>
        </div>
      </PanelBox>
    )
  }

}
